<template>
  <div class="timing-task">
    <!-- 筛选按钮 -->
    <div class="filter-container">
      <!-- 设置个人号 -->
      <el-select v-model.trim="taskState" placeholder="任务状态" size="small" style="width: 100px" clearable>
        <el-option v-for="item in taskStates" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>



      <el-select v-model.trim="sendType" placeholder="发送类型" size="small" style="width: 100px" clearable>
        <el-option label="主动发送" value="0"/>
        <el-option label="被动发送" value="1"/>
      </el-select>

      <el-select v-model.trim="circle_type" placeholder="朋友圈类型" size="small" style="width: 100px" clearable>
        <el-option value="普通"/>
        <el-option value="广告"/>
        <el-option value="续费客户"/>
      </el-select>
      
      <el-select
        v-model.trim="deleteState"
        style="margin-left: 8px; width: 100px"
        placeholder="是否删除"
        size="small"
        clearable
      >
        <el-option
          v-for="deleteItem in deleteStates"
          :key="deleteItem.label"
          :label="deleteItem.label"
          :value="deleteItem.value"
        />
      </el-select>
      <!-- 文字内容 -->
      <el-input
        v-model="searchTaskName"
        size="small"
        style="width: 160px; margin-left: 8px"
        clearable
        placeholder="请输入任务描述"
        class="input-with-select"
      ></el-input>
      <!-- 文字内容 -->
      <el-input
        v-model="searchTextContent"
        size="small"
        style="width: 180px; margin-left: 8px"
        clearable
        placeholder="请输入文字内容"
        class="input-with-select"
      >
        <!-- <span slot="prepend">文字内容</span> -->
      </el-input>

      <!-- 设置时间段 -->
      <el-date-picker
        v-model="timePick"
        style="margin-left: 8px; width: 360px"
        size="small"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
      ></el-date-picker>

      <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <!-- 数据展示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="circlesList"
      border
      fit
      style="width: 99%"
      highlight-current-row
    >
      <el-table-column prop="taskname" label="任务描述" align="center" min-width="100px">
        <template slot-scope="{ row }">
          <div class="circle-content" v-html="row.task_name"></div>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="朋友圈内容" align="center" min-width="180px">
        <template slot-scope="{ row }">
          <div class="circle-content" v-html="decodeCircleContent(row.remarks)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="朋友圈类型" align="center" min-width="70px">
        <template slot-scope="{ row }">
          {{ row.circle_type }}
        </template>
      </el-table-column>

      <el-table-column prop="remarks" label="发送类型" align="center" min-width="70px">
        <template slot-scope="{ row }">
          <p v-if="row.send_type==0">主动发送</p>
          <p v-else-if="row.send_type==1">被动发送</p>
        </template>
      </el-table-column>

      <el-table-column prop="remarks" label="来源用户" align="center" min-width="120px">
        <template slot-scope="{ row }">
          <div class="userInfo" @click="goUser(row)" style="display: flex;flex-direction: row;">
            <div style="margin: 0px 10px;">
              <img :src="row.origin_avatar" style="width: 40px;"/>
            </div>
            <div style="line-height: 50px;">
              {{ row.origin_name }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="media" label="客服号"min-width="120px">
            <template slot-scope="scope">
              {{ scope.row.origin_wechatid_name }}
            </template>
          </el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ new Date(row.createTime).toLocaleString() }}</span>
        </template>
      </el-table-column> -->

      <el-table-column prop="execute_time" label="预计发送时间" align="center" min-width="120px">
        <template slot-scope="{ row }">
          <p>{{ row.execute_time }}</p>
          <span v-if="isValidTime(row.end_time)" style="text-align: center;"> - </span>
          <p v-if="isValidTime(row.end_time)">{{ row.end_time }}</p>
        </template>
      </el-table-column>

      <el-table-column prop="" label="成功/发送数" align="center" min-width="100px">
        <template slot-scope="{ row }">
          <span v-text="row.doingsize ? row.doingsize : 0"></span>
          /
          <span v-text="row.totalsize"></span>
          <el-button
            style="margin-left: 10px"
            class="el-icon-info"
            type="text"
            @click="showTaskDetail(row)"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column prop="likesize" label="点赞/评论数" align="center" min-width="100px">
        <template slot-scope="{ row }">
          <span v-text="row.likesize ? row.likesize : 0"></span>
          /
          <span v-text="row.commentsize ? row.commentsize : 0"></span>
        </template>
      </el-table-column>

      <el-table-column prop="deleted" label="任务状态" align="center" min-width="100px">
        <template slot-scope="{ row }">
          <div style="margin-bottom: 6px;">
            <span v-if="row.state === 1">开启中</span>
            <span v-else-if="row.state === 0" style="color: blue">已完成</span>
            <span v-else-if="row.state === 2" style="color: red">部分未完成</span>
            <span v-else>{{ row.state }}</span>
          </div>
          <div style="margin-top: 6px;">
            <span v-if="row.deleted === 'false'">未删除</span>
            <span v-else style="color: red">已删除</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" min-width="120px" width="120px"class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <div v-if="row.status != 'deleted'" class="action-buttons">
            <el-button size="mini" class="action-button" type="primary" @click="taskDetail(row)">详情</el-button>
            <el-button v-if="row.state === 1" size="mini" class="action-button" type="primary" @click="editTask(row, $index)">修改</el-button>
            <el-button size="mini" class="action-button" type="warning" @click="resendTask(row)">重发</el-button>
            <el-button size="mini" class="action-button" type="danger" @click="deleteTask(row, $index)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNo"
      :limit.sync="pageSize"
      @pagination="getCirclesList"
    />

    <el-dialog append-to-body title="朋友圈详情" class="circle-detail-dialog" :visible.sync="detailDialog" width="80%">
      <CircleDetail v-if="detailDialog" />
    </el-dialog>

    <!-- 子任务列表 -->
    <el-dialog
      append-to-body
      title="任务详情"
      class="circle-detail-dialog"
      :visible.sync="taskDetailDialog"
      width="80%"
    >
      <el-table
        :key="tableKey"
        :data="taskDetailList"
        border
        fit
        max-height="100%"
        style="width: 99%"
        highlight-current-row
      >
        <el-table-column prop="wechatid" label="微信id" align="center"></el-table-column>
        <el-table-column prop="wechatid" label="微信昵称" align="center">
          <template slot-scope="{ row }">
            <span v-text="allWechatNameMap[row.wechatid] || ''"></span>
          </template>
        </el-table-column>
        <el-table-column prop="execute_time" label="执行时间" align="center"></el-table-column>
        <el-table-column prop="state" label="是否执行" align="center">
          <template slot-scope="{ row }">
            <span v-text="row.state === 0 ? '已执行' : '待执行'"></span>
          </template>
        </el-table-column>
        <el-table-column prop="results" label="执行结果" align="center"></el-table-column>

        <el-table-column label="操作" align="center" min-width="120px" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-button
              :disabled="row.results === 'true' || row.state === 1"
              size="mini"
              type="warning"
              @click="resendChildTask(row.id)"
            >
              重发
            </el-button>
            <!-- <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="deleteTask(row, $index)">
              删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import dayjs from 'dayjs'

import Pagination from '@/components/Pagination'
import CircleDetail from './CircleDetail.vue'

import { getAllDevices } from '@/api/admin/device'
import { queryCircleTask, deleteCircleTask, queryCircleTaskInfo, resendCircle } from '@/api/front/circle'

export default {
  name: 'TimingTask',
  components: { Pagination, CircleDetail },
  data() {
    return {
      taskStates: [
        {
          label: '开启中',
          value: 1
        },
        {
          label: '已完成',
          value: 0
        }
      ], // 任务状态
      taskState: '', // 任务状态
      deleteState: '', // 任务状态
      sendType: '',
      circle_type: '',
      deleteStates: [
        {
          label: '已删除',
          value: true
        },
        {
          label: '未删除',
          value: false
        }
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      timePick: '',
      searchTextContent: '', // 文本内容
      searchTaskName: '', // 任务名称

      listLoading: true, // 正在获取数据
      circlesList: [], // 表格中的数据
      detailDialog: false,

      taskDetailDialog: false, // 展示子任务详情
      taskDetailList: [], // 子任务列表
      allWechatNameMap: {},

      total: 0, // 数据总数
      pageNo: 1, // 页
      pageSize: 20, // 页面大小
      tableKey: 0 // 表的key 改变可以重新渲染表
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser'
    })
  },
  created() {
    // 获取朋友圈列表
    this.getCirclesList()
    // 获取所有的设备
    getAllDevices(this.currentUser.SupplierId, this.currentUser.UnionId).then((res) => {
      const wm = {}
      res.data.forEach((x) => {
        wm[x.wechatid] = x.wechatnick
      })
      this.allWechatNameMap = wm
    })
  },
  methods: {
    goUser(row) {
      let jump={
        wxid:row.origin_wechatid,
        fid:row.origin_friendid,
      }
      this.$router.replace({ name: 'conversation',query:{
        jump:JSON.stringify(jump)
      }})
    },
    // 校验时间是否有效
    isValidTime(timestamp) {
      if (!timestamp) return false
      const date = new Date(timestamp)
      return !isNaN(date.getTime())
    },
    // 分页查询设备
    getCirclesList() {
      let startTime = ''
      let endTime = ''
      if (this.timePick) {
        startTime = dayjs(this.timePick[0]).format('YYYY-MM-DD HH:mm')
        endTime = dayjs(this.timePick[1]).format('YYYY-MM-DD HH:mm')
      }
      queryCircleTask(
        this.currentUser.SupplierId,
        this.pageNo,
        this.pageSize,
        this.taskState,
        this.searchTextContent,
        startTime,
        endTime,
        null,
        this.deleteState,
        this.searchTaskName,
        this.sendType,
        this.circle_type,
        [],
      )
        .then((res) => {
          this.circlesList = res?.data?.rows || []
          this.total = res?.data?.records || 0
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 搜索
    handleFilter() {
      this.pageNo = 1
      this.getCirclesList()
    },
    // 解析朋友圈内容
    decodeCircleContent(content) {
      try {
        const jContent = JSON.parse(content)
        const { circleType, textContent, attachtContent } = jContent
        let AttachContent = []
        if (attachtContent) {
          AttachContent = attachtContent.split(',')
        }
        if (circleType === 'text') {
          return `<p>${textContent}</p>`
        } else if (circleType === 'picture') {
          let imgStr = ''
          for (const ac of AttachContent) {
            imgStr = imgStr + `<img style="width:80px;height:80px;padding:4px;object-fit:cover;" src="${ac}" />`
          }
          return `<p>${textContent}</p>
              <div style="display:flex;flex-wrap:wrap;">${imgStr}</div>
              `
        } else if (circleType === 'video') {
          return `<p>${textContent}</p>
            <video style="padding:5px;" src="${attachtContent}" controls></video>
            `
        } else {
          // 链接
          const title = AttachContent[1]
          const imgUrl = AttachContent[2]
          return `<p>${textContent}</p>
            <div style="display:flex;align-items:center;">
            <img style="width:30%;margin-right:5px;" src="${imgUrl}" />
            <span>${title}</span>
            </div>
            `
        }
      } catch (error) {
        return content
      }
    },
    // 删除任务
    deleteTask(row) {
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCircleTask(row.id).then(() => {
            this.getCirclesList()
          })
        })
        .catch(() => {})
    },
    // 重发
    resendTask(row) {
      this.$store.commit('circleManager/SET_CIRCLE_DATA', row)
      this.$store.commit('circleManager/SET_EDIT_MODE', false)
      this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'sendCircle')
    },
    // 编辑任务
    editTask(row) {
      this.$store.commit('circleManager/SET_CIRCLE_DATA', row)
      this.$store.commit('circleManager/SET_EDIT_MODE', true)
      this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'sendCircle')
    },
    // 朋友圈详情
    taskDetail(row) {
      this.$store.commit('circleManager/SET_CIRCLE_DATA', row)
      this.detailDialog = true
    },
    // 获取并展示子任务
    showTaskDetail(row) {
      this.taskDetailList = []
      queryCircleTaskInfo(row.id)
        .then((res) => {
          if (res.code === 0 && res.data) {
            this.taskDetailList = res.data
            this.taskDetailDialog = true
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 重发子任务
    resendChildTask(rid) {
      if (rid) {
        resendCircle(rid)
          .then((res) => {
            if (res.code === 0) {
              this.$message.success('任务已经下达！')
            }
          })
          .catch((err) => {
            this.$message.err(err)
          })
      } else {
        this.$message.warning('没有id不能重发！')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.timing-task {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .filter-container {
    margin-bottom: 20px;
  }
  ::v-deep .circle-content {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    p {
      padding: 5px;
      text-align: start;
    }
  }
  .action-buttons {
    display: grid;
    gap: 12px; /* 按钮间距 */
    justify-content: center;
  }

  .action-button {
    width: 60px; /* 统一按钮宽度 */
    margin: 0 !important; /* 清除默认边距 */
  }
}
.userInfo:hover{
  cursor: pointer;
}
</style>
